package dao;

import classes.entidade.AreaAuditada;
import conexao.GerenciadorConexao;
import erro.ConexaoException;
import erro.ConsultaException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

/**
 *
 * @author roberta.m.carvalho
 */
public class AreaAuditadaDao {

    private GerenciadorConexao g;

    public AreaAuditadaDao() {
        g = GerenciadorConexao.getInstancia();
    }

    public void inserirAreaAuditada(AreaAuditada aa) throws ConexaoException, ConsultaException {
        String sql = "INSERT INTO areaauditada(nome) "
                + "VALUES (?)";
        try {
            PreparedStatement pstm = (PreparedStatement) g.connect().prepareStatement(sql);
            pstm.setString(1, aa.getNome());
            pstm.executeUpdate();
        } catch (SQLException ex) {
            throw new ConsultaException(ex);
        } finally {
            g.disconnect();
        }
    }

    public ArrayList<AreaAuditada> listarArea() throws ConexaoException, ConsultaException {
        ArrayList<AreaAuditada> lista = new ArrayList<AreaAuditada>();
        AreaAuditada area;
        String sql = "SELECT * "
                + "FROM areaauditada order by nome asc";
        try {
            Statement stm = (Statement) g.connect().createStatement();
            ResultSet rs = stm.executeQuery(sql);
            while (rs.next()) {
                area = new AreaAuditada();
                area.setIdAreaAuditada(rs.getInt("idareaAuditada"));
                area.setNome(rs.getString("nome"));
                lista.add(area);
            }
        } catch (SQLException ex) {
            throw new ConsultaException(ex);
        } finally {
            g.disconnect();
        }
        return lista;
    }

    public void alterarArea(AreaAuditada aa) throws ConexaoException, ConsultaException {
        String sql = "UPDATE areaauditada SET nome=? WHERE idareaAuditada=?";
        try {
            PreparedStatement pstm = (PreparedStatement) g.connect().prepareStatement(sql);
            pstm.setString(1, aa.getNome());
            pstm.setInt(2, aa.getIdAreaAuditada());
            pstm.executeUpdate();
        } catch (SQLException ex) {
            throw new ConsultaException(ex);
        } finally {
            g.disconnect();
        }
    }

    public void deletarArea(AreaAuditada aa) throws ConexaoException, ConsultaException {
        String sql = "DELETE FROM areaauditada where idareaAuditada =?";
        try {
            PreparedStatement pstm = (PreparedStatement) g.connect().prepareStatement(sql);
            pstm.setInt(1, aa.getIdAreaAuditada());
            pstm.executeUpdate();
        } catch (SQLException ex) {
            throw new ConsultaException(ex);
        } finally {
            g.disconnect();
        }
    }
}
